/*
Copyright 2011 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.catonine.swing.memstat;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;

/**
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 * 
 */
public class MemStatComponent extends JPanel implements ActionListener {
	private static final long serialVersionUID = 8427003598539072334L;
	private Timer timer = null;
	private final JProgressBar memoryDisplay;
	private final String freePrefix;
	private final String totalPrefix;
	private final String maxPrefix;

	public MemStatComponent(final String freePrefix, final String totalPrefix,
			final String maxPrefix) {
		super();
		this.freePrefix = freePrefix;
		this.totalPrefix = totalPrefix;
		this.maxPrefix = maxPrefix;
		memoryDisplay = new JProgressBar();
		memoryDisplay.setStringPainted(true);
		add(memoryDisplay);
		timer = new Timer(999, this);
		timer.start();
		setMaximumSize(getPreferredSize());
	}

	public void stop() {
		timer.stop();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Runtime r = Runtime.getRuntime();
		final long freeMemory = r.freeMemory();
		final long maxMemory = r.maxMemory();
		final long totalMemory = r.totalMemory();
		final long usedMemory = totalMemory - freeMemory;
		final String freeMemoryString = format(freeMemory);
		final String totalString = format(totalMemory);
		final String maxString = format(maxMemory);
		final String usedMemoryString = format(usedMemory);

		memoryDisplay.setString(usedMemoryString + "/" + maxString);
		float percent = ((float) (totalMemory - freeMemory) / (float) maxMemory) * 100;
		memoryDisplay.setValue((int) percent);
		memoryDisplay.setToolTipText(this.freePrefix + freeMemoryString + ", "
				+ this.totalPrefix + totalString + ", " + this.maxPrefix
				+ maxString);

		validate();
	}

	private String format(final long value) {
		long truncatedValue = value;
		String suffix = "";
		if (truncatedValue > 1024) {
			suffix = " KiB";
			truncatedValue = truncatedValue / 1024;
		}
		if (truncatedValue > 1024) {
			suffix = " MiB";
			truncatedValue = truncatedValue / 1024;
		}
		if (truncatedValue > 1024) {
			suffix = " GiB";
			truncatedValue = truncatedValue / 1024;
		}
		return truncatedValue + suffix;
	}

}
